<template>
  <div class="login">
    <div class="error">{{ message }}</div>
    <form>
      <div class="label">
        <input
          type="text"
          name="username"
          v-model.trim="username"
          placeholder="请输入用户名"
        />
        <input
          type="password"
          name="password"
          v-model.trim="password"
          placeholder="请输入密码"
        />
      </div>
      <div class="submit">
        <input type="submit" @click.prevent="login" value="登录" />
      </div>
    </form>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
export default {
  name: "UserLogin",
  data() {
    return {
      username: "",
      password: "",
      message: "",
    };
  },
  methods: {
    ...mapMutations("user", ["saveUser"]),
    checkForm() {
      if (!this.username || !this.password) {
        this.message = "用户名和密码不能为空";
        return false;
      }
      return true;
    },
    login() {
      this.message = "";
      if (!this.checkForm()) return;
      this.axios
        .post("/user/login", {
          username: this.username,
          password: this.password,
        })
        .then((response) => {
          if (response.data.code === 200) {
            this.saveUser(response.data.data);
            this.username = "";
            this.password = "";
            // 如果存在查询参数
            if (this.$route.query.redirect) {
              const redirect = this.$route.query.redirect;
              // 跳转至进入登录页前得路由
              this.$router.replace(redirect);
            } else {
              // 否则跳转至首页
              this.$router.replace("/");
            }
          } else if (response.data.code === 500) {
            this.message = "用户登陆失败";
          } else if (response.data.code === 400) {
            this.message = "用户名或密码错误";
          }
        })
        .catch((error) => {
          console.log(error.message);
        });
    },
  },
};
</script>

<style scoped>
.login {
  margin: 50px auto;
  width: 380px;
}

.login input {
  padding: 20px;
  width: 90%;
  font-size: 20px;
  margin: 18px 0px;
  color: rgb(78, 77, 77);
  float: left;
  cursor: pointer;
  outline: none;
  background: rgba(240, 235, 235, 0.438);
  transition: all 0.3s ease-out;
  border: solid 1px rgb(161, 161, 161);
  border-radius: 30px;
  transition: 2s;
}

.login input:hover {
  color: rgb(50, 104, 167);
  background: rgba(116, 176, 255, 0.753);
}

.login .submit {
  text-align: center;
}
.login input[type="submit"] {
  padding: 17px 17px;
  color: #fff;
  background: #3a8efd;
  border: solid 1px #3a8efd;
  cursor: pointer;
  font-size: 18px;
  transition: all 0.5s ease-out;
  outline: none;
  width: 100%;
}

.login .submit input[type="submit"]:hover {
  background: #1546cc;
  border: solid 1px #1546cc;
}
.login .error {
  color: red;
  font-weight: bold;
}
</style>
